package com.utils;

import com.common.GmallConfig;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class PhonexUtil {

    // 根据实体类 创建表
    public static void checkTable(String tableName, Class t, String pk, String ext) throws SQLException {

        Field[] fields = t.getDeclaredFields();
        System.out.println(fields.length+"----------");
        Connection connection = DriverManager.getConnection(GmallConfig.PHOENIX_SERVER);

        //主键不存在,则给定默认值
        if (StringUtils.isEmpty(pk)) {
            pk = "id";
        }
        //扩展字段不存在,则给定默认值
        if (StringUtils.isEmpty(ext)) {
            ext = "";
        }
        //创建字符串拼接对象,用于拼接建表语句SQL
        StringBuilder createSql = new StringBuilder("create table if not exists " + "JMALL" + "." + tableName + "(");
        //将列做切分,并拼接至建表语句SQL中
       // String[] fieldsArr = fields.split(",");
        for (int i = 0; i < fields.length; i++) {
            String field = fields[i].getName();
            if (pk.equals(field)) {
                createSql.append(field).append(" varchar primary key ");
            } else {
                createSql.append("info.").append(field).append(" varchar");
            }
            if (i < fields.length - 1) {
                createSql.append(",");
            }
        }
        createSql.append(")");
        createSql.append(ext);

        try {
            //执行建表语句在Phoenix中创建表
            System.out.println(createSql);
            PreparedStatement ps = connection.prepareStatement(createSql.toString());
            ps.execute();
            ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("建表失败！！！");
        }
    }
}
